<template>
    <!-- hidden PageHeaderWrapper title demo -->
    <page-header-wrapper :title="false" :content="$t('form.basic-form.basic.description')">
      <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
        <a-upload name="file" :multiple="true" :customRequest="customUpload" :headers="headers" @change="handleChange">
          <a-button>
            <a-icon type="upload" />
            断点续传
          </a-button>
        </a-upload>
      </a-card>
    </page-header-wrapper>
  </template>
  
  <script>
  import axios from 'axios'
  
  const BASE_URL = 'http://192.168.0.232:8080'
  
  export default {
    name: 'BaseForm',
    data() {
      return {
        headers: {
          authorization: 'authorization-text',
        },
        form: this.$form.createForm(this),
      }
    },
    methods: {
      async customUpload(options) {
        const { file } = options
        const fileId = this.generateFileId(file)
        const { uploadedChunks, shouldUpload } = await this.checkUploaded(fileId)
  
        if (!shouldUpload) {
          alert('文件已存在，无需重复上传。')
          return
        }
  
        const chunkSize = 1 * 1024 * 1024 // 1MB
        const chunkCount = Math.ceil(file.size / chunkSize)
        for (let i = 0; i < chunkCount; i++) {
          if (uploadedChunks.includes(i)) continue // 跳过已上传的片段
          const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize)
          await this.uploadChunk(chunk, i, fileId, options.onProgress)
        }
  
        await this.mergeChunks(fileId, chunkCount)
        options.onSuccess()
      },
      generateFileId(file) {
        // 提取文件扩展名
        const extension = file.name.split('.').pop()
        // 使用文件名（不包括扩展名）、文件大小和最后修改时间来生成基础 ID
        const baseId = `${file.name.slice(0, file.name.lastIndexOf('.'))}-${file.size}-${file.lastModified}`
        // 返回包含原始扩展名的文件 ID
        return `${baseId}.${extension}`
      },
      async checkUploaded(fileId) {
        try {
          // 发送 GET 请求到 /check 接口，查询已上传的文件片段
          const response = await axios.get(`${BASE_URL}/check`, {
            params: { filename: fileId },
          })
          // 假设服务器返回的数据格式为 { uploadedChunks: [0, 1, 2], shouldUpload: true }
          // 直接返回这个数据结构
          return response.data
        } catch (error) {
          console.error('Check uploaded chunks failed:', error)
          // 发生错误时，可以选择返回一个默认值，或者根据实际情况处理错误
          return { uploadedChunks: [], shouldUpload: false }
        }
      },
      async uploadChunk(chunk, index, fileId, onProgress) {
        const formData = new FormData()
        formData.append('file', chunk)
        formData.append('chunkIndex', index.toString())
        formData.append('filename', fileId)
  
        try {
          try {
            const response = await axios.post(`${BASE_URL}/upload`, formData)
            console.log(response.data)
          } catch (error) {
            console.error(error)
          }
        } catch (error) {
          console.error('Upload chunk failed:', error)
          throw error // 抛出错误以便可以在调用处捕获
        }
      },
  
      async mergeChunks(fileId, chunkCount) {
        const formData = new FormData()
        formData.append('filename', fileId)
        formData.append('chunkCount', chunkCount.toString())
  
        try {
          const response = await axios.post(`${BASE_URL}/merge`, formData)
          console.log(response.data) // 处理合并后的响应
        } catch (error) {
          console.error('Merge chunks failed:', error)
          throw error // 抛出错误以便可以在调用处捕获
        }
      },
      handleChange(info) {
        // 处理文件状态改变的事件
        if (info.file.status === 'done') {
          console.log(`${info.file.name} file uploaded successfully`)
        } else if (info.file.status === 'error') {
          console.log(`${info.file.name} file upload failed.`)
        }
      },
    },
  }
  </script>
  